/*
	Programação Concorrente
	Trabalho 3
	Turma A

	Adilson Abreu Couto Rapozo Junior ( n. USP: 6402336 )
	Luiz Alfredo Bertoni ( n. USP: 6418834 )
	Rodrigo Fernandes da Costa ( n. USP: 6793073 )
*/

#include "main.h"


/*allocate memory for all data needed*/
strut * allocStrut(int n_vars) {

    strut * ret = (strut *) malloc(sizeof(strut));
    
    if(ret == NULL) {
        printf("Error: Cannot allocate memory\n");
        exit(1);
    }

    double ** matrix;
    int i, j;
    
    
    matrix = (double **) malloc(n_vars*sizeof(double *));
    
    if(matrix == NULL) {
        printf("Error: Cannot allocate memory\n");
        exit(1);
    }
    
    for(i = 0; i < n_vars; i++) {
        matrix[i] = (double *) malloc((n_vars+1)*sizeof(double));
        if(matrix[i] == NULL) {
            printf("Error: Cannot allocat memory\n");
            exit(1);
        }
    }
    
    for(i = 0; i < n_vars; i++) {
        for(j = 0; j < n_vars+1; j++) {
            matrix[i][j] = 0;
        }
    }

    ret->matrix = matrix;
    ret->J_ORDER = n_vars;

    return ret;
}

/*read system*/
strut * loadStrut(char * pfile) {

    strut * ret;
    int n_vars;
    int row_test;
    double error;
    int iter;
    
    int i, j;
    
    FILE * in = fopen(pfile, "r");
    
    if(in == NULL) {
        fprintf(stderr, "Cannot open file\n");
        exit(1);
    }
    
    /* start loading data */
    fscanf(in, "%d", &n_vars);
    fscanf(in, "%d", &row_test);
    fscanf(in, "%lf", &error);
    fscanf(in, "%d", &iter);
    
    ret = allocStrut(n_vars);

    for(i = 0; i < ret->J_ORDER; i++) {
        for(j = 0; j < (ret->J_ORDER); j++) {
            fscanf(in, "%lf", &(ret->matrix[i][j]));
        }
    }
    
    for(i = 0; i < ret->J_ORDER; i++)
        fscanf(in, "%lf", &(ret->matrix[i][ret->J_ORDER]));
    
    
    /* close file pointer */
    fclose(in);
    
    /* loading all data left*/
    ret->J_ROW_TEST = row_test;
    ret->J_ERROR = error;
    ret->J_ITE_MAX = iter;      
    return ret;
}

/* prints all data (A and B)*/
void printSystem(strut *sis) {
    
    int i, j;
    
    for(i = 0; i < sis->J_ORDER; i++) {
        for(j = 0; j < (sis->J_ORDER+1); j++) {
            printf("%lf ",sis->matrix[i][j]);
        }
        printf("\n");
    }
}

/* prints the elemets of the matrix */
void printMatrix(strut *sis) {
    
    int i, j;
    
    for(i = 0; i < sis->J_ORDER; i++) {
        for(j = 0; j < (sis->J_ORDER); j++) {
            printf("%lf ",sis->matrix[i][j]);
        }
        printf("\n");
    }
}

/* frees all allocated memory*/
void cleansys(strut *sis) {
    
    int i;
    
    for(i = 0; i < sis->J_ORDER; i++)
        free(sis->matrix[i]);
    
    free(sis->matrix);
    
    sis->J_ORDER = 0;
}
